import { cat } from "@shimotsuki/core";

import Crypto from 'crypto-es';

type RequestData = Record<string, any>;

// 获取签名
export const getCommonSign = (data: RequestData = {}): { sign: string, timestamp: string } => {
    let timestamp = (~~(Date.now() / 1000) + cat.store.global.diffServerTimer).toString(); //10位时间戳
    let data_timestamp: RequestData = { ...data, 'X-Timestamp': timestamp };
    let keys = Object.keys(data_timestamp);

    const nonce = keys.sort().reduce((prev, cur) => {
        // 排除paginate.limit paginate.page category_id=0 status=0
        if (
            !(
                ['paginate.limit', 'paginate.page'].includes(cur) ||
                (['category_id', 'status'].includes(cur) && data_timestamp[cur] == 0) ||
                typeof data_timestamp[cur] === 'object'
            )
        ) {
            prev += `${prev.length ? '&' : ''}${cur}=${data_timestamp[cur]}`;
        }

        return prev;
    }, '');

    let sign = Crypto.SHA1(Crypto.MD5(nonce + cat.env.secret).toString()).toString();

    return { sign, timestamp };
};